<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file license.txt or that can be found at 
 * http://code.google.com/p/billboardce/wiki/License.
 *
 * @package    Default_DevicesController
 * @category   Controller
 * @license    http://code.google.com/p/billboardce/wiki/License New BSD License
 * @version    SVN: $Id: $
 */

/**
 * Main interface for dealing with devices
 *
 * @package    Default_DevicesController
 * @category   Controller
 */
class DevicesController extends Zend_Controller_Action 
{   
    public function indexAction()
    {
       $this->view->acl = array(
           'add'     => $this->_helper->hasAccess('add'),
           'edit'    => $this->_helper->hasAccess('edit'),
           'details' => $this->_helper->hasAccess('details'),
           'delete'  => $this->_helper->hasAccess('delete')
       );
        
        $device = new Device();
        
        $allDevices = $device->getDevicesForAccount(Zend_Auth::getInstance()->getIdentity()->accountId, false)->toArray();
        
        $slidestreamDevice = new Slidestream_Device();
        $slidestream = new Slidestream();
        
        $slidestreams = $slidestream->getSlidestreamsForAccount(Zend_Auth::getInstance()->getIdentity()->accountId)->toArray();
        
        $slidestreamList = array();
        foreach ($slidestreams as $s) {
            $slidestreamList[$s['slidestreamId']] = $s;
        }

        $deviceIds = array();
        foreach ($allDevices as $d) {
            $deviceIds[] = $d['deviceId'];
        }
        
        if (count($deviceIds) > 0) {
            
            $slidestreamDeviceMap = array();
            
            $dba = $slidestreamDevice->getAdapter();
            $mappings = $slidestreamDevice->fetchAll($dba->quoteInto('deviceId IN (?)', $deviceIds));
            foreach ($mappings as $m) {
                $slidestreamDeviceMap[$m->deviceId] = $m->slidestreamId;
            }
        }
        
        foreach ($allDevices as &$d) {
            $d['typeName'] = $device->getDeviceTypeName($d['type']);
            if (isset($slidestreamDeviceMap[$d['deviceId']]) && isset($slidestreamList[$slidestreamDeviceMap[$d['deviceId']]])) {
                $d['assigned'] = $slidestreamList[$slidestreamDeviceMap[$d['deviceId']]];
            }
        }
        
        $this->view->devices = $allDevices;
        $this->view->messages = $this->_helper->flashMessenger->getMessages();
        $this->_helper->pageTitle('Devices');
    }
    
    public function detailsAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->deviceId)) {
            throw new Ot_Exception_Input('No device ID given');
        }
        
        $deviceId = $get->deviceId;
        
        $device = new Device();
        
        $thisDevice = $device->find($deviceId);
        
        if (is_null($thisDevice)) {
            throw new Ot_Exception_Data('Device not found');
        }
        
        if ($thisDevice->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
            throw new Ot_Exception_Data('Device not found!');
        }
        
        $thisDevice = $thisDevice->toArray();
        $thisDevice['typeName'] = $device->getDeviceTypeName($thisDevice['type']);
        
        $this->view->device = $thisDevice;
        
        $this->_helper->pageTitle('Device Details - ' . $thisDevice['name']);
        
        $config = Zend_Registry::get('config');
        
        $this->view->headScript()->appendFile('http://maps.google.com/maps/api/js?indexing=false&sensor=false');
    }
    
    public function editAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->deviceId)) {
            throw new Ot_Exception_Input('No device ID given');
        }
        
        $deviceId = $get->deviceId;
        
        $device = new Device();
        
        $thisDevice = $device->find($deviceId);
        
        if (is_null($thisDevice)) {
            throw new Ot_Exception_Data('Device not found');
        }
        
        if ($thisDevice->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
            throw new Ot_Exception_Data('Device not found!');
        }
        
        $form = $device->form($thisDevice);
        
        if ($this->_request->isPost()) {
            if ($form->isValid($_POST)) {

                $data = $form->getValues();
                $data['accountId'] = Zend_Auth::getInstance()->getIdentity()->accountId;
                
                $device->update($data);
                
                $this->_helper->flashMessenger->addMessage('Device saved successfully');
                $this->_helper->redirector->gotoRoute(array(), 'devices', true);
            }
        }
        
        $this->view->form = $form;
        $this->_helper->pageTitle('Edit Device');
        
        $this->view->headScript()->appendFile('http://maps.google.com/maps/api/js?indexing=false&sensor=false');
    }
    
    public function addAction()
    {
        $device = new Device();
        
        // id of slidestream to redirect to if it's set
        $slidestreamId = $this->_getParam('redirect');
        
        $form = $device->form();
        
        if ($this->_request->isPost()) {
            if ($form->isValid($_POST)) {
                
                $data = $form->getValues();
                $data['accountId'] = Zend_Auth::getInstance()->getIdentity()->accountId;
                
                $deviceId = $device->insert($data);

                // if it was a redrirect, go back to the slidestream
                if (!is_null($slidestreamId)) {

                    $this->_helper->redirector->gotoRoute(array('action' => 'details', 'slidestreamId' => $slidestreamId, 'redirect' => $deviceId), 'slidestream', true);
                    
                } else {
                    $this->_helper->flashMessenger->addMessage('Device added successfully');
                    $this->_helper->redirector->gotoRoute(array(), 'devices', true);
                }
            }
        }
        
        $this->view->form = $form;
        $this->_helper->pageTitle('Add New Device');
        
        $this->view->headScript()->appendFile('http://maps.google.com/maps/api/js?indexing=false&sensor=true');
        $this->view->headScript()->appendFile('http://code.google.com/apis/gears/gears_init.js');
    }
    
    public function deleteAction()
    {
        $get = Zend_Registry::get('getFilter');
        
        if (!isset($get->deviceId)) {
            throw new Ot_Exception_Input('No slide steram ID given');
        }
        
        $deviceId = $get->deviceId;
        
        $device = new Device();
        
        $thisDevice = $device->find($deviceId);
        
        if (is_null($thisDevice)) {
            throw new Ot_Exception_Data('Device not found');
        }
        
        if ($thisDevice->accountId != Zend_Auth::getInstance()->getIdentity()->accountId) {
            throw new Ot_Exception_Data('Device not found!');
        }
        
        $form = Ot_Form_Template::delete('deleteDevice');
        
        if ($this->_request->isPost() && $form->isValid($_POST)) {

            $where = $device->getAdapter()->quoteInto('deviceId = ?', $deviceId);
            $device->delete($where);
            
            $this->_helper->flashMessenger->addMessage('Device deleted successfully');
            $this->_helper->redirector->gotoRoute(array(), 'devices', true);
        }
        
        $this->view->form = $form;
        $this->view->device = $thisDevice;
        $this->_helper->pageTitle('Delete Device');
    }   
}